package com.snow.springboot.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {
	public static List<String> readFile(MultipartFile file) {
		InputStreamReader streamReader = null;
		BufferedReader bufferedReader = null;
		List<String> list = new ArrayList<String>();
		try {
			InputStream inputStream = file.getInputStream();
			streamReader = new InputStreamReader(inputStream);
			bufferedReader = new BufferedReader(streamReader);
			String line = null;
			while ((line = bufferedReader.readLine()) != null) {
				list.add(line.trim());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 批量写入文件
	 * 
	 * @param file
	 * @param datas
	 */
	public static void writeByte(String file, List<String> datas) {
		FileOutputStream fis = null;
		BufferedWriter bw = null;
		try {
			fis = new FileOutputStream(file, true);
			bw = new BufferedWriter(new OutputStreamWriter(fis));
			if (datas != null && datas.size() > 0) {
				for (int i = 0; i < datas.size(); i++) {
					bw.write(datas.get(i));
					bw.newLine();
				}
				System.out.println("over");
			} else {
				System.out.println("数据为空！");
			}
			bw.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (bw != null)
					bw.close();
				if (fis != null)
					fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 单行写入文件
	 * 
	 * @param file
	 * @param data
	 */
	public static void writeByte(String file, String data) {
		FileOutputStream fis = null;
		BufferedWriter bw = null;
		try {
			fis = new FileOutputStream(file, true);
			bw = new BufferedWriter(new OutputStreamWriter(fis));
			if (null != data && !"".equals(data)) {
				bw.write(data);
				bw.newLine();
				System.out.println("over");
			} else {
				System.out.println("数据为空！");
			}
			bw.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (bw != null)
					bw.close();
				if (fis != null)
					fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static List<String> ReadFile(String filename) {
		File file = new File(filename);
		BufferedReader reader = null;
		List<String> result = new ArrayList<String>();
		System.out.println("startTime:" + System.currentTimeMillis());
		try {
			reader = new BufferedReader(new FileReader(file), 5 * 1024 * 1024); // 如果是读大文件
			String tempString = null;
			while ((tempString = reader.readLine()) != null) {
				result.add(tempString);
			}
			System.out.println("endTime:" + System.currentTimeMillis());
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}
	

}
